import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 用户信息接口
interface UserInfo {
  id: number
  username: string
  email: string
  realName: string
  role: string
  avatar?: string
}

/**
 * 用户状态管理Store
 */
export const useUserStore = defineStore('user', () => {
  // ==================== 状态数据 ====================
  
  const userInfo = ref<UserInfo | null>(null)
  const token = ref<string | null>(null)
  const isLoggedIn = ref(false)

  // ==================== 计算属性 ====================
  
  const userId = computed(() => userInfo.value?.id || null)
  const username = computed(() => userInfo.value?.username || '')
  const userRole = computed(() => userInfo.value?.role || '')

  // ==================== 方法 ====================
  
  /**
   * 初始化用户状态（从localStorage恢复）
   */
  const initUserState = () => {
    const savedToken = localStorage.getItem('token')
    const savedUserInfo = localStorage.getItem('userInfo')
    
    if (savedToken && savedUserInfo) {
      try {
        token.value = savedToken
        userInfo.value = JSON.parse(savedUserInfo)
        isLoggedIn.value = true
      } catch (error) {
        // 解析失败，清除无效数据
        clearUserState()
      }
    }
  }

  /**
   * 设置用户信息
   */
  const setUserInfo = (user: UserInfo, authToken: string) => {
    userInfo.value = user
    token.value = authToken
    isLoggedIn.value = true
    
    // 持久化到localStorage
    localStorage.setItem('token', authToken)
    localStorage.setItem('userInfo', JSON.stringify(user))
  }

  /**
   * 清除用户状态
   */
  const clearUserState = () => {
    userInfo.value = null
    token.value = null
    isLoggedIn.value = false
    
    // 清除localStorage
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }

  /**
   * 更新用户信息
   */
  const updateUserInfo = (updates: Partial<UserInfo>) => {
    if (userInfo.value) {
      userInfo.value = { ...userInfo.value, ...updates }
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
    }
  }

  /**
   * 获取当前用户ID（兼容旧代码）
   */
  const getCurrentUserId = (): number => {
    // 如果有真实用户信息，返回真实ID
    if (userInfo.value?.id) {
      return userInfo.value.id
    }

    // 如果没有用户信息，抛出错误
    throw new Error('用户未登录，无法获取用户ID')
  }

  // ==================== 初始化 ====================
  
  // 应用启动时初始化用户状态
  initUserState()

  // ==================== 返回状态和方法 ====================
  
  return {
    // 状态
    userInfo,
    token,
    isLoggedIn,
    
    // 计算属性
    userId,
    username,
    userRole,
    
    // 方法
    setUserInfo,
    clearUserState,
    updateUserInfo,
    getCurrentUserId,
    initUserState
  }
})
